package br.edu.ufcg.lsd.wbis.ui.server;

import static br.edu.ufcg.lsd.wbis.ui.server.ControllerAccesser.getController;
import static br.edu.ufcg.lsd.wbis.ui.server.Util.getEquivalentLevel;
import static br.edu.ufcg.lsd.wbis.ui.server.Util.getEquivalentStatus;
import br.edu.ufcg.lsd.wbis.control.user.User;
import br.edu.ufcg.lsd.wbis.ui.client.beans.RootCreationStatus;
import br.edu.ufcg.lsd.wbis.ui.client.beans.UserInfo;
import br.edu.ufcg.lsd.wbis.ui.client.services.GeneralService;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class GeneralServiceImpl extends RemoteServiceServlet implements GeneralService {

	private static final long serialVersionUID = -7497033518409087428L;

	/**
	 * {@inheritDoc}
	 */
	public UserInfo login(UserInfo info) {
		try {
			User user = getController().authenticateUser(info.getLogin(), info.getPassword());
			UserInfo brandNewInfo = new UserInfo();
			brandNewInfo.setLogin(info.getLogin());
			brandNewInfo.setPassword(info.getPassword());
			brandNewInfo.setName(user.getName());
			brandNewInfo.setEmail(user.getEmail());
			brandNewInfo.setLevel(getEquivalentLevel(user.getLevel()));
			brandNewInfo.setAuthorized(user.isAuthorized());
			return brandNewInfo;
		} catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public UserInfo register(UserInfo userInfo) {
		try {
			User user = getController().addCommonUser(userInfo.getLogin(), userInfo.getPassword(), userInfo.getName(), userInfo.getEmail());
			UserInfo returnInfo = new UserInfo();
			returnInfo.setName(user.getName());
			returnInfo.setEmail(user.getEmail());
			returnInfo.setLogin(user.getLogin());
			returnInfo.setLevel(getEquivalentLevel(user.getLevel()));
			returnInfo.setAuthorized(user.isAuthorized());
			return returnInfo;
		} catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public RootCreationStatus getRootUserStatus() {
		try {
			return getEquivalentStatus(getController().getRootUserStatus());
		} catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

}
